package com.demo.jvm.chapter2.heap;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import java.util.ArrayList;
import java.util.List;

public class HeapOOM {

  static class OOMObject {

  }

  /**
   * vm option:
   * -Xms4m -Xmx8m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/Users/lwg/SouceCode/private/lie-flat-club/example-demo/src/main/java/com/demo/jvm
   */
  public static void main(String[] args) {
    List<OOMObject> list = new ArrayList<OOMObject>();
    while (true) {
      MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();

      MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();
      MemoryUsage nonHeapMemoryUsage = memoryMXBean.getNonHeapMemoryUsage();

      System.out.println("堆的初始值：" + heapMemoryUsage.getInit() / 1024 / 1024 + "MB");
      System.out.println("堆的当前使用值：" + heapMemoryUsage.getUsed() / 1024 / 1024 + "MB");
      System.out.println("堆的已提交值：" + heapMemoryUsage.getCommitted() / 1024 / 1024 + "MB");
      System.out.println("堆的最大值：" + heapMemoryUsage.getMax() / 1024 / 1024 + "MB");
      list.add(new OOMObject());
      System.out.println(list.size());
    }
  }
}
